package org.ypx.center.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ypx.center.service.IUserInfoService;
import org.ypx.center.service.IUserService;
import org.ypx.db.entity.User;
import org.ypx.db.entity.UserInfo;
import org.ypx.db.entity.UserRole;
import org.ypx.db.mapper.UserMapper;
import org.ypx.db.mapper.UserRoleMapper;
import org.ypx.shared.common.Message;
import org.ypx.shared.common.Result;
import org.ypx.shared.service.vo.UserInfoVO;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by tingwen on 2017/3/17.
 */
@Service
public class UserInfoServiceImpl extends BaseServiceImpl<UserInfo> implements IUserInfoService {

    private Result<List<UserInfoVO>> results = new Result<>();

    @Autowired
    private IUserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public Result<List<UserInfoVO>> selectUserInfo(UserInfo userInfo1, User user1, UserRole userRole) {
        List<UserInfoVO> userInfoVOs = new ArrayList<>();
        List<User> users = userMapper.select(user1);
        users.forEach(user -> {
            UserInfoVO userInfoVO = new UserInfoVO();
            UserInfo userInfo = mapper.selectByPrimaryKey(user.getUserId());
            if (userInfo != null) {
                userInfoVO.setUserNo(userInfo.getUserNo());
                userInfoVO.setUsername(userInfo.getUsername());
                userInfoVO.setDepartment(userInfo.getDepartment());
                userInfoVO.setGrade(userInfo.getGrade());
                userInfoVO.setKlass(userInfo.getKlass());
            }
            userInfoVO.setUserId(user.getUserId());
            userInfoVO.setEmail(user.getEmail());
            userInfoVO.setMobile(user.getMobile());
            userInfoVO.setRoleName(userService.findRoles(user.getLoginName()));
            userInfoVOs.add(userInfoVO);
        });
        results.setData(userInfoVOs);
        return results;
    }

    @Override
    public Result<List<UserInfo>> saveUserInfo(UserInfo userInfo, User user, UserRole userRole) {
        userService.save(user);
        User user1 = new User();
        user1.setLoginName(user.getLoginName());
        user = userMapper.selectOne(user1);
        Long userId = user.getUserId();
        userInfo.setUserId(userId);
        userRole.setUserId(userId);
        this.save(userInfo);
        userRoleMapper.insert(userRole);
        result.setMessage(Message.SUCCESS);
        return result;
    }
}
